package edu.hue.jk.service;

import edu.hue.jk.Mapper.UserDao;
import edu.hue.jk.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.util.List;
@Service
public class UserService {
    @Autowired
    private UserDao userMapper;

    public String login(int role,String username, String password, Model model){
        //登录逻辑函数
        try{
            User userExistN = userMapper.findByName(username);
            if(userExistN!=null){
                String userExistP = userMapper.findPswByName(username);

                if(userExistP.equals(password)){
                    if(role==1)
                        return "index";
                    else{
                        model.addAttribute("msg","该用户不是宿舍管理员！");
                        return "login";
                    }
                }else {
                    model.addAttribute("msg","密码错误！");
                    return "login";
                }
            }else {
                model.addAttribute("msg","用户不存在！");
                return "login";
            }
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public String regist(String username,String password,Model model){
        //注册逻辑函数
        try {
            User userExist = userMapper.findByName(username);
            if (username.equals("")){
                model.addAttribute("msg","用户名不能为空");
                return "login";
            }else if (password.equals("")){
                model.addAttribute("msg","密码不能为空");
                return "login";
            }else if (userExist!=null){
                model.addAttribute("msg","用户名已存在");
                return "login";
            }else{
                User user=new User();
                user.setUsername(username);
                user.setPassword(password);
                userMapper.insert(user);
                model.addAttribute("msg","注册成功");
                return "login";
            }
        }catch (Exception e){
            e.printStackTrace();
            return e.getMessage();
        }

    }

    public List<User> findAll(){
        List<User> list = userMapper.findAll();
        return list;
    }

}
